import java.util.Arrays;

/**
* @description: 1049. 最后一块石头的重量 II
* @author hewei
* @date 2022/10/7 14:59
* @version 1.0
*/

public class LastStoneWeightII {

    public static void main(String[] args) {
        int[] nums = {91};
        System.out.println(new LastStoneWeightII().lastStoneWeightII(nums));
    }

    public int lastStoneWeightII1(int[] stones) {
        int sum = Arrays.stream(stones).sum();
        int n = stones.length;
        boolean[][] dp = new boolean[n + 1][sum / 2 + 1];
        for (int i = 0; i < n + 1; i++) {
            dp[i][0] = true;
        }
        for (int i = 1; i < n + 1; i++) {
            for (int j = 1; j < sum / 2 + 1; j++) {
                dp[i][j] = dp[i - 1][j];
                if (j >= stones[i - 1]) dp[i][j] = dp[i - 1][j - stones[i - 1]] || dp[i][j];
            }
        }
        for (int i = sum / 2; i >= 0; i--) {
            if (dp[n][i]) return sum - i - i;
        }
        return 0;
    }

    public int lastStoneWeightII(int[] stones) {
        int sum = Arrays.stream(stones).sum();
        boolean[] dp = new boolean[sum / 2 + 1];
        dp[0] = true;
        for (int stone : stones) {
            for (int j = sum / 2; j >= stone; j--) {
                dp[j] = dp[j] || dp[j - stone];
            }
        }
        for (int i = sum / 2; ; i--) {
            if (dp[i]) return sum - i - i;
        }
    }
}